/**
 * @Author: ls <ls-mac>
 * @Date:   2019-08-13 23:16:25
 * @Last modified by:   ls-mac
 * @Last modified time: 2019-10-14 15:00:21
 */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import {
  Row,
  Col,
  Card,
  Checkbox,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Popover,
  Popconfirm,
  TimePicker,
  Table,
  Modal,
  message,
  Badge,
  Divider,
  Upload,
} from 'antd';
import SimpleTable from 'components/SimpleTable';
import styles from './enterprise.less';

import PageHeaderLayout from '../../layouts/PageHeaderLayout';

const FormItem = Form.Item;

const { Option } = Select;

const CreateForm = Form.create()(prop => {
  const {
    state,
    form,
    props,
    handleCancel,
    renderOptionsP,
    renderOptionsV,
    renderOptionsC,
    renderOptionsI,
    onChangeP,
    renderStoreFeatures,
  } = prop;
  const { modalVisible, type, record } = state;
  const { getFieldDecorator } = form;
  const {
    dispatch,
    dict: { dictList },
    storeList: { dictStoreDetail },
  } = props;

  const detailInfo = type === 'edit' ? dictStoreDetail : {};

  const handleOk = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return false;
      const params = {
        ...fieldsValue,
        storeFeatures:
          fieldsValue.storeFeatures instanceof Array
            ? fieldsValue.storeFeatures.join(',')
            : fieldsValue.storeFeatures,
      };
      if (record.id) {
        params.id = record.id;
      }
      dispatch({
        type: 'storeList/dictStoreAddOrEdit',
        payload: params,
        callback: res => {
          if (res.success) {
            message.success(type === 'add' ? '新增门店成功' : '修改门店成功');
            handleCancel();
          } else {
            message.info(res.errorDesc);
          }
        },
      });
    });
  };

  const s = detailInfo?.storeFeatures;
  let a = [];
  if (s) {
    a = s.split(',');
  }
  console.log(s);
  return (
    <Modal
      title={type === 'add' ? '新增门店' : '修改门店'}
      visible={modalVisible}
      onOk={() => handleOk()}
      onCancel={() => handleCancel()}
      className=""
      okText="提交"
      width="850px"
      destroyOnClose
    >
      <Form layout="inline">
        <Row gutter={{ lg: 24 }}>
          <Col md={8} sm={24}>
            <FormItem label="门店名称">
              {getFieldDecorator('name', {
                initialValue: detailInfo?.name,
                rules: [{ required: true, message: '请输入门店名称' }],
              })(<Input placeholder="" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="联系电话">
              {getFieldDecorator('storePhone', {
                initialValue: detailInfo?.storePhone,
                rules: [{ required: true, message: '请输入联系电话' }],
              })(<Input placeholder="" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="门店类型">
              {getFieldDecorator('storeType', {
                initialValue: detailInfo?.storeType,
                rules: [{ required: true, message: '请输入门店类型' }],
              })(
                <Select
                  showSearch
                  placeholder="请选择"
                  style={{ width: 150 }}
                  filterOption={(input, option) =>
                    option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                  }
                >
                  <Option key="0" value="0">
                    全部
                  </Option>
                  <Option key="1" value="1">
                    普通
                  </Option>
                  <Option key="2" value="2">
                    高端
                  </Option>
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ lg: 24 }}>
          <Col md={8} sm={24}>
            <FormItem label="所在省份">
              {getFieldDecorator('provinceId', {
                initialValue: detailInfo?.provinceId,
                rules: [{ required: true, message: '请选择所在省份' }],
              })(
                <Select
                  showSearch
                  onSelect={onChangeP}
                  placeholder="请选择"
                  style={{ width: 150 }}
                  filterOption={(input, option) =>
                    option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                  }
                >
                  {renderOptionsP()}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="所在城市">
              {getFieldDecorator('cityId', {
                initialValue: detailInfo?.cityId,
                rules: [{ required: true, message: '请选择所在城市' }],
              })(
                <Select placeholder="请选择" style={{ width: 150 }}>
                  {renderOptionsC()}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="详细地址">
              {getFieldDecorator('address', {
                initialValue: detailInfo?.address,
                rules: [{ required: true, message: '请输入详细地址' }],
              })(<Input placeholder="" />)}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ lg: 24 }}>
          <Col md={8} sm={24}>
            <FormItem label="公休日&#12288;">
              {getFieldDecorator('vocationDay', {
                initialValue: detailInfo?.vocationDay,
                rules: [{ required: true, message: '请选择所在省份' }],
              })(
                <Select
                  showSearch
                  placeholder="请选择"
                  style={{ width: 150 }}
                  filterOption={(input, option) =>
                    option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                  }
                >
                  {renderOptionsV()}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="体检机构">
              {getFieldDecorator('institutionId', {
                initialValue: detailInfo?.institutionId,
                rules: [{ required: true, message: '请选择所在城市' }],
              })(
                <Select placeholder="请选择" style={{ width: 150 }}>
                  {renderOptionsI()}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="提前预约天数">
              {getFieldDecorator('appointmentBeforeDays', {
                initialValue: detailInfo?.appointmentBeforeDays,
                rules: [{ required: true, message: '请输入提前预约天数' }],
              })(<Input style={{ width: 126 }} />)}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ lg: 24 }}>
          <Col md={12} sm={24}>
            <FormItem label="&nbsp;门店特性">
              {getFieldDecorator('storeFeatures', {
                initialValue: a,
              })(
                <Select mode="multiple" style={{ width: 300 }} placeholder="请选择">
                  {renderStoreFeatures(dictList)}
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
      </Form>
    </Modal>
  );
});

@connect(({ storeList, dict, loading }) => ({
  storeList,
  dict,
  loading: loading.models.storeList,
}))
@Form.create()
export default class TableList extends PureComponent {
  state = {
    modalVisible: false,
    type: 'add',
    record: {},
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'storeList/fetch',
      payload: {
        cityName: '',
        institutionName: '',
        storeName: '',
        pageIndex: '1',
        pageSize: '10',
      },
    });

    // 查询省份
    dispatch({
      type: 'dict/dictProvinceList',
      payload: {},
    });

    // 查询城市
    dispatch({
      type: 'dict/dictCityList',
      payload: {},
    });

    // 查询门店特性
    dispatch({
      type: 'dict/dictList',
      payload: { type: 'STORE_FEATURE' },
    });

    // 查询体检机构
    dispatch({
      type: 'dict/dictInstitutionList',
      payload: {},
    });
  }

  // 分页
  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const params = {
        pageIndex: pagination.current,
        pageSize: pagination.pageSize,
        ...fieldsValue,
      };

      dispatch({
        type: 'storeList/fetch',
        payload: params,
      });
    });
  };

  // 重置
  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    dispatch({
      type: 'storeList/fetch',
      payload: {
        cityName: '',
        institutionName: '',
        storeName: '',
        pageIndex: '1',
        pageSize: '10',
      },
    });
  };

  handleSearch = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const params = {
        pageIndex: 0,
        pageSize: 10,
        ...fieldsValue,
      };

      dispatch({
        type: 'storeList/fetch',
        payload: params,
      });
    });
  };

  handleEdit = record => {
    const { dispatch } = this.props;
    dispatch({
      type: 'storeList/dictStoreDetail',
      payload: { id: record.id },
    });
    this.setState({
      type: 'edit',
      modalVisible: true,
      record,
    });
  };

  handleCancel = () => {
    this.setState({
      modalVisible: false,
    });
    this.handleFormReset();
  };

  handleAdd = () => {
    this.setState({
      modalVisible: true,
    });
  };

  handleDelete = record => {
    const { dispatch } = this.props;
    dispatch({
      type: 'storeList/dictStoreDelete',
      payload: { id: record.id },
      callback: res => {
        if (res.success) {
          message.success('删除成功');
        } else {
          message.info(res.errorDesc);
        }
        this.handleFormReset();
      },
    });
  };

  reColumns = () => {
    const that = this;

    return [
      {
        title: '门店',
        dataIndex: 'name',
      },
      {
        title: '地址',
        dataIndex: 'address',
      },
      {
        title: '电话',
        dataIndex: 'storePhone',
      },
      {
        title: '公休日',
        dataIndex: 'vocationDay',
        render: v => {
          switch (v) {
            case '1':
              return <span>无休</span>;
            case '2':
              return <span>周末</span>;
            case '3':
              return <span>周一</span>;
            case '4':
              return <span>周二</span>;
            case '5':
              return <span>周三</span>;
            case '6':
              return <span>周四</span>;
            case '7':
              return <span>周五</span>;
            case '8':
              return <span>周六</span>;
            case '9':
              return <span>周日</span>;
            default:
              return '';
          }
        },
      },
      {
        title: '体检机构',
        dataIndex: 'institutionName',
      },
      {
        title: '省份',
        dataIndex: 'provinceName',
      },
      {
        title: '城市',
        dataIndex: 'cityName',
      },
      {
        title: '提前预约天数',
        dataIndex: 'appointmentBeforeDays',
      },
      {
        title: '门店类型',
        dataIndex: 'storeType',
        render: v =>
          v === '0' ? <span>全部</span> : v === '1' ? <span>普通</span> : <span>高端</span>,
      },
      {
        title: '门店特性',
        dataIndex: 'storeFeaturesDesc',
      },
      {
        title: '操作',
        render: (val, record) => (
          <div>
            <a onClick={() => that.handleEdit(record)}>修改</a>
            <br />
            <a onClick={() => that.handleDelete(record)}>删除</a>
          </div>
        ),
      },
    ];
  };

  onChangeP = v => {
    // 查询城市
    const { dispatch } = this.props;
    dispatch({
      type: 'dict/dictCityList',
      payload: { provinceId: v },
    });
  };

  renderOptionsI = () => {
    const {
      dict: { institutionList },
    } = this.props;
    const options = institutionList.map(v => (
      <Option key={v.id} value={v.id}>
        {v.name}
      </Option>
    ));
    return options;
  };

  renderOptionsP = () => {
    const {
      dict: { provinceList },
    } = this.props;
    const options = provinceList.map(v => (
      <Option key={v.id} value={v.id}>
        {v.name}
      </Option>
    ));
    return options;
  };

  renderOptionsC = () => {
    const {
      dict: { cityList },
    } = this.props;
    const options = cityList.map(v => (
      <Option key={v.id} value={v.id}>
        {v.name}
      </Option>
    ));
    return options;
  };

  renderStoreFeatures = d => {
    const newList = d.map(value => {
      const v = value;
      return <Option value={v.id}>{v.dictValue}</Option>;
    });

    return newList;
  };

  renderOptionsV = () => {
    const list = [
      {
        key: '1',
        value: '无休',
      },
      {
        key: '2',
        value: '周末',
      },
      {
        key: '3',
        value: '周一',
      },
      {
        key: '4',
        value: '周二',
      },
      {
        key: '5',
        value: '周三',
      },
      {
        key: '6',
        value: '周四',
      },
      {
        key: '7',
        value: '周五',
      },
      {
        key: '8',
        value: '周六',
      },
      {
        key: '9',
        value: '周日',
      },
    ];
    const options = list.map(v => (
      <Option key={v.key} value={v.key}>
        {v.value}
      </Option>
    ));
    return options;
  };

  renderSearchForm = () => {
    const { form } = this.props;
    const { getFieldDecorator } = form;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row
          gutter={{
            md: 8,
            lg: 24,
            xl: 48,
          }}
        >
          <Col md={8} sm={24}>
            <FormItem label="城市名称">
              {getFieldDecorator('cityName')(<Input placeholder="请输入城市名称" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="机构名称">
              {getFieldDecorator('institutionName')(<Input placeholder="请输入机构名称" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="门店名称">
              {getFieldDecorator('storeName')(<Input placeholder="请输入门店名称" />)}
            </FormItem>
          </Col>
        </Row>
        <Row
          gutter={{
            md: 8,
            lg: 24,
            xl: 48,
          }}
        >
          <Col md={24} sm={24}>
            <div
              style={{
                overflow: 'hidden',
                height: '40px',
                lineHeight: '40px',
              }}
            >
              <span
                style={{
                  float: 'right',
                }}
              >
                <Button type="primary" htmlType="submit">
                  查询
                </Button>
                <Button
                  style={{
                    marginLeft: 8,
                  }}
                  onClick={this.handleFormReset}
                >
                  重置
                </Button>
              </span>
            </div>
          </Col>
        </Row>
      </Form>
    );
  };

  render() {
    const columns = this.reColumns();
    const {
      storeList: { data },
      loading,
    } = this.props;

    return (
      <PageHeaderLayout>
        <Card bordered={false} style={{ paddingBottom: '20px' }}>
          <div>
            <div className={styles.tableListForm}>{this.renderSearchForm()}</div>
            <div>
              <Button type="primary" icon="plus" onClick={this.handleAdd}>
                新增
              </Button>
            </div>
            <SimpleTable
              selectedRows={false}
              loading={loading}
              data={data}
              columns={columns}
              onSelectRow={false}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
        <CreateForm {...this} />
      </PageHeaderLayout>
    );
  }
}
